package com.theory.sms.controller.api;

import com.theory.common.exception.Assert;
import com.theory.common.exception.BusinessException;
import com.theory.common.result.R;
import com.theory.common.result.ResponseEnum;
import com.theory.common.util.RandomUtils;
import com.theory.common.util.RegexValidateUtils;
import com.theory.sms.service.SmsService;
import com.theory.sms.client.CoreUserInfoClient;
import com.theory.sms.util.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信管理")
@RestController
@RequestMapping("/sms/api")
//@CrossOrigin
@Slf4j
public class ApiSmsApiController {

    @Resource
    private SmsService smsService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CoreUserInfoClient coreUserInfoClient;


    @ApiOperation("批量给不同号码发送相同的验证码")
    @PostMapping("/batchSendSameCode")
    public R batchSendSameCode(
            @ApiParam(value = "手机号码", required = true)
            @RequestBody String... mobiles) {

//        String[] str = new String[mobiles.length];

        for (String mobile : mobiles) {
            //MOBILE_NULL_ERROR(-202, "手机号不能为空"),
//            Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
            //MOBILE_ERROR(-203, "手机号不正确"),
            Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);
        }

        String[] str = {RandomUtils.getSixBitRandom()};

        smsService.send(SmsProperties.TEMPLATE_ID, mobiles, str);


        try {
            for (String mobile : mobiles) {
                redisTemplate.opsForValue().set("srb:sms:code:" + mobile, str[0], 5, TimeUnit.MINUTES);
            }
        } catch (Exception e) {
            // 这里看业务场景，抛异常的话，前台会显示redis异常，但是短信是已经发送了的，这是没有存入到redis，前台显示redis，如果只打印不抛出的话，那前台就显示发送成功
            // 这里我选择报错，即结束业务，前台还是显示的短信发送成功
//            log.error("redis服务器异常" + e.getMessage());
            throw new BusinessException(ResponseEnum.REDIS_ERROR, e);
        }


        return R.ok().message("短信发送成功");
    }

    @ApiOperation("批量给多个号码发送不相同的验证码")
    @PostMapping("/batchSend")
    public R batchSend(
            @ApiParam(value = "手机号码", required = true)
            @RequestBody String... mobiles) {

        for (String mobile : mobiles) {
//            Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);
//            String[] code = {RandomUtils.getSixBitRandom()};
//            String[] phone = {mobile};
//            smsService.send(SmsProperties.TEMPLATE_ID, phone, code);
//
//            try {
//                redisTemplate.opsForValue().set("srb:sms:code:" + mobile, code[0], 5, TimeUnit.MINUTES);
//            } catch (Exception e) {
//                throw new BusinessException(ResponseEnum.REDIS_ERROR, e);
//            }
            send(mobile);
        }

        return R.ok().message("短信发送成功");

    }

    @ApiOperation("给单个手机发送验证码")
    @GetMapping("/send/{mobile}")
    public R send(
            @ApiParam(value = "手机号码", required = true)
            @PathVariable String mobile) {

        // 校验手机号码是否存在

            boolean result = coreUserInfoClient.checkMobile(mobile);

        Assert.isTrue(!result,ResponseEnum.MOBILE_EXIST_ERROR);

        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);
        String[] code = {RandomUtils.getSixBitRandom()};
        String[] phone = {mobile};

        // 为了省钱，先不调用腾讯云的api，直接放到redis里面，去redis里面找验证码就可以了，或者是直接打印到控制台
//        smsService.send(SmsProperties.TEMPLATE_ID, phone, code);

        log.info(mobile + "的验证码为：" + Arrays.toString(code));


        try {
            redisTemplate.opsForValue().set("srb:sms:code:" + mobile, code[0], 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new BusinessException(ResponseEnum.REDIS_ERROR, e);
        }


        return R.ok().message("短信发送成功");

    }
}
